#!/bin/bash

# Check if the correct number of arguments are provided
if [ "$#" -lt 5 ]; then
    echo "Usage: $0 <ALIYUN_REGISTRY> <ALIYUN_NAME_SPACE> <ALIYUN_REGISTRY_USER> <ALIYUN_REGISTRY_PASSWORD> <IMAGE1> [IMAGE2 ...]"
    exit 1
fi

# Set environment variables from command line arguments
ALIYUN_REGISTRY="$1"
ALIYUN_NAME_SPACE="$2"
ALIYUN_REGISTRY_USER="$3"
ALIYUN_REGISTRY_PASSWORD="$4"

# Docker login to Aliyun registry
docker login -u "$ALIYUN_REGISTRY_USER" -p "$ALIYUN_REGISTRY_PASSWORD" "$ALIYUN_REGISTRY"

# Shift the first four arguments so we can iterate over the images
shift 4

# Process each image provided as an argument
for line in "$@"; do
  # Skip empty lines
  [[ -z "$line" ]] && continue

  echo "docker pull $line"
  docker pull "$line"

  # Extract platform information if present
  platform=$(echo "$line" | awk -F'--platform[ =]' '{if (NF>1) print $2}' | awk '{print $1}')
  echo "platform is $platform"

  # Determine platform prefix
  if [ -z "$platform" ]; then
    platform_prefix=""
  else
    platform_prefix="${platform//\//_}_"
  fi
  echo "platform_prefix is $platform_prefix"

  # Get full image name and tag
  image=$(echo "$line" | awk '{print $NF}')
  image_name_tag=$(echo "$image" | awk -F'/' '{print $NF}')

  # Create new image name with Aliyun registry and namespace
  new_image="$ALIYUN_REGISTRY/$ALIYUN_NAME_SPACE/$platform_prefix$image_name_tag"
  
  echo "docker tag
